package com.sx.springbootshiro.controller;

import com.sx.springbootshiro.model.LoginUserVB;
import com.sx.springbootshiro.service.LoginUserService;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/loginUser")
public class LoginUserController {
    private Logger logger = LogManager.getLogger(LoginUserController.class);

    @Autowired
    private LoginUserService loginUserService;

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @GetMapping("/selectLoginUserVBSByUseful")
    public List<LoginUserVB> selectLoginUserVBSByUseful(){
        return loginUserService.selectLoginUserVBSByUseful();
    }

    @GetMapping("/selectLoginUserVBByNicknamePassword")
    public LoginUserVB selectLoginUserVBByNicknamePassword(@Param("user_nickname") String user_nickname,
                                                           @Param("user_password") String user_password){
        return loginUserService.selectLoginUserVBByNicknamePassword(user_nickname,user_password);
    }

    @GetMapping("/insetLoginUserVB")
    public boolean insetLoginUserVB(@Param("loginUserVB") LoginUserVB loginUserVB){

        logger.debug("loginUserVB 对象=== "+loginUserVB);

        return loginUserService.insetLoginUserVB(loginUserVB);
    }

    @GetMapping("/login")
    public String login(@Param("user_nickname") String user_nickname,
                        @Param("user_password") String user_password){
        logger.debug("准备登陆开始 === ");
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user_nickname,
                user_password
        );

        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        }catch (AuthenticationException e) {
            e.printStackTrace();
            return "账号或密码错误！";
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return "没有权限";
        }
        return "login success";
    }

    //注解验角色和权限
    @RequiresRoles("admin")
    @RequiresPermissions("add")
    @RequestMapping("/index")
    public String index() {
        return "index!";
    }

    @GetMapping("/error")
    public String error(){
        return "出现异常";
    }


}
